
var   gulp = require("gulp"),
      connect = require("gulp-connect"),
      sass = require('gulp-sass'),
      babel = require('gulp-babel'),
      uglify = require('gulp-uglify'),
      cssmin = require('gulp-cssmin'),
      proxy = require("http-proxy-middleware")


sass.compiler = require('node-sass');

gulp.task("connect", async () => {


      return connect.server({
            root: "dist",
            livereload: true,
            port: 3000,
            middleware : function(){
                  return [
                        // 表示在地址栏里面输入的东西是什么 : 
                        proxy('/pxx',  {
                            target: 'https://mobile.yangkeduo.com/proxy/api/api/spike/promotion/list/spike',//代理的目标地址
                            changeOrigin:true,
                            pathRewrite:{//路径重写规则 
                                '^/pxx':''
                            }
                        })
                    ]
            }
      });
});

// 目标 : 页面自动刷新 ;

gulp.task("html", async () => {
      return gulp.src(["./src/*.html"])
            .pipe(gulp.dest("./dist/"))
            .pipe(connect.reload());
})

// sass 编译功能;
gulp.task("sass", async () => {
      return gulp.src(["./src/styles/*.scss"])
            .pipe(sass().on('error', sass.logError))
            .pipe(gulp.dest("./dist/styles/"))
            .pipe(connect.reload())
})
gulp.task("sass-build", async () => {
      return gulp.src(["./src/styles/*.scss"])
            .pipe(sass().on('error', sass.logError))
            .pipe(cssmin())
            .pipe(gulp.dest("./dist/styles/"))
})
gulp.task("javascripts", async () => {
      await gulp.src(["./src/javascripts/*.js"])
            .pipe(babel({
                  presets: ['@babel/env']
            }))
            .pipe(uglify())
            .pipe(gulp.dest("./dist/javascripts"))
})

gulp.task("javascripts-dev", async () => {
      await gulp.src(["./src/javascripts/*.js"])
            .pipe(gulp.dest("./dist/javascripts"))
            .pipe(connect.reload())
})

gulp.task("watch", async () => {
      await gulp.watch("./src/*.html", gulp.series("html"));
      await gulp.watch("./src/styles/*.scss", gulp.series("sass"));
      await gulp.watch("./src/javascripts/*.js", gulp.series("javascripts-dev"));
})

gulp.task("default", gulp.parallel("watch", "connect"));

gulp.task("build", gulp.series("javascripts", "sass-build"))